package service

import (
	"TheTearAfter/component"
	"TheTearAfter/models"
	"TheTearAfter/util"
	"fmt"
	"math/rand"
	"sort"
	"sync"

	"time"
)

/**
 * @File : message.go
 * @Description : 信息相关服务
 * @Author : chen
 * @Date : 2024/4/16
 */

// 爬取数据
func messageClaw(keyword string) (messageList []*models.MessageBlock, err error) {
	urlHead := "https://newsnetwork.mayoclinic.org/search/?search=eye%%20"
	urlHaid := "&pg=%d"

	fmt.Println("Claw Url: " + urlHead + keyword + urlHaid)
	Queryer := component.NewMessageClawer(urlHead + keyword + urlHaid)
	_, err = Queryer.ClawUrl(1, "ch-analytics-search-result-link ch-search-result-title")
	if err != nil {
		return
	}

	messageList, err = Queryer.ClawMessage()
	return
}

// 更新数据
func MessageBlockUpdata(classList []*models.MessageTypeClass) (err error) {

	// 获取旧数据
	oldList, err := models.GetAllMessageBlock()
	if err != nil {
		return
	}
	// 协程池
	var wg sync.WaitGroup

	// 拿到所有数据再更新
	for _, class := range classList {
		wg.Add(1)
		go func(nowClass *models.MessageTypeClass) {
			defer wg.Done()
			nowList, err := messageClaw(nowClass.Name)
			sort.Sort(models.MessageBlockList(nowList))

			if err != nil {
				util.ErrPrintRespon("models.messageClaw", err)
				return
			}

			// 添加链接 自动分类
			for _, now := range nowList {
				now, err := models.CreateAMessageBlock(now)
				if err != nil {
					util.ErrPrintRespon("models.CreateAMessageBlock", err)
					return
				}

				// 添加分类链接
				nowLink := &models.MessageTypeClass_Link_MessageBlock{
					MessageTypeClassID: nowClass.ID,
					MessageBlockID:     now.ID,
				}

				_, err = models.CreateMessageBlockToMessageTypeClass(nowLink)
				if err != nil {
					util.ErrPrintRespon("models.CreateMessageBlockToMessageTypeClass", err)
					return
				}
			}
		}(class)

	}
	wg.Wait()

	// 清除
	for _, old := range oldList {
		err = models.DeleteMessageBlockByID(old.ID, true)
		if err != nil {
			return
		}

	}

	fmt.Println("\nClawer Done")
	return
}

// 更新信息类
func MessageTypeClassUpdata(newList []*models.MessageTypeClass) (err error) {
	// 清理并注入
	oldList, err := models.GetAllMessageTypeClass()
	if err != nil {
		return
	}
	oldLinkList, err := models.GetALLMessageTypeClass_Link_MessageBlock()
	if err != nil {
		return
	}

	// 注入
	for _, new := range newList {
		_, err = models.CreateAMessageTypeClass(new)
		if err != nil {
			return
		}
	}

	// 删除
	for _, old := range oldList {
		err = models.DeleteMessageTypeClassByID(old.ID)
		if err != nil {
			return
		}
	}
	for _, oldLink := range oldLinkList {
		err = models.DeleteMessageTypeClass_Link_MessageBlockByID(oldLink.ID, true)
		if err != nil {
			return
		}
	}
	return
}

// 定时更新服务
func TickUpdata(startTime int, minTime int) {
	// 区间随机定时
	go func() {
		// 初始 300s 间隔
		ticker := time.NewTicker(time.Duration(startTime) * time.Second)
		rand.Seed(time.Now().UnixNano())
		for {
			<-ticker.C
			ticker.Reset(time.Duration(minTime+rand.Intn(10)) * time.Hour)
			classList, err := models.GetAllMessageTypeClass()
			if err != nil {
				util.ErrPrintRespon("models.GetAllMessageTypeClass", err)
				return
			}
			err = MessageBlockUpdata(classList)
			if err != nil {
				util.ErrPrintRespon("service.MessageBlockUpadta", err)
				return
			}
		}
	}()
}

// 获取所有类型块
func GetAllMessageTypeClass() (itemList []*models.MessageTypeClass, err error) {
	itemList, err = models.GetAllMessageTypeClass()
	return
}

// 根据类型获取信息块
func GetMessageBlockByTypeID(id int) (blockList []*models.MessageBlock, err error) {
	// 获取 id
	linkList, err := models.GetALLMessageTypeClass_Link_MessageBlockByMessageTypeClass(uint(id))
	if err != nil {
		return
	}

	// 获取块
	for _, link := range linkList {
		block, err := models.GetMessageBlockByID(link.MessageBlockID)
		if err != nil {
			return nil, err
		}
		blockList = append(blockList, block)
	}
	return
}
